// 导入 types.js 文件
import types from "../../types";

const state = {
  ctitle: (typeof sessionStorage.getItem("ctitle") == "object") ? JSON.parse(sessionStorage.getItem("ctitle")) : {
    ctitle: {}
  }, //公共头部
  userinfo: JSON.parse(localStorage.getItem("userinfo")) || '',
  cityinfo: JSON.parse(sessionStorage.getItem("cityinfo")) || '',
  realnamestatus: JSON.parse(sessionStorage.getItem("realnamestatus")) || false,
  wxopenid: JSON.parse(sessionStorage.getItem("wxopenid")) || '', //openid
  wxcode: JSON.parse(sessionStorage.getItem("wxcode")) || '', //code
}

// 定义 getters
var getters = {
  ctitle(state) {
    return state.ctitle
  },
  userinfo(state) {
    return state.userinfo
  },
  cityinfo(state) {
    return state.cityinfo
  },
  realnamestatus(state) {
    return state.realnamestatus
  },
  wxopenid(state) {
    return state.wxopenid
  },
  wxcode(state) {
    return state.wxcode
  },
}

const actions = {
  CTITLE({
    commit,
    state
  }) {
    // 此处提交的事件与下方 mutations 中的 types.CTITLE 对应
    //与原来 commit('ctitle') 的原理相同，只是把类型名换成了常量
    commit(types.CTITLE)
  },
  USERINFO({
    commit,
    state
  }) {
    commit(types.USERINFO)
  },
  CITYINFO({
    commit,
    state
  }) {
    commit(types.CITYINFO)
  },
  REALNAMESTATUS({
    commit,
    state
  }) {
    commit(types.REALNAMESTATUS)
  },
  WXOPENID({
    commit,
    state
  }) {
    commit(types.WXOPENID)
  },
  WXCODE({
    commit,
    state
  }) {
    commit(types.WXCODE)
  },
}

const mutations = {
  // 此处的事件为上方 actions 中的 commit(types.CTITLE)
  [types.CTITLE](state, data) { //标题信息
    sessionStorage.setItem("ctitle", JSON.stringify(data));
    state.ctitle = data;
  },
  [types.USERINFO](state, data) { //登陆信息
    if (data) {
      localStorage.setItem("userinfo", JSON.stringify(data));
      state.userinfo = data;
    } else {
      localStorage.removeItem("userinfo", JSON.stringify(data));
      state.userinfo = '';
    }

  },
  [types.CITYINFO](state, data) { //城市信息
    sessionStorage.setItem("cityinfo", JSON.stringify(data));
    state.cityinfo = data;
  },
  [types.REALNAMESTATUS](state, data) { //认证标志
    sessionStorage.setItem("realnamestatus", JSON.stringify(data));
    state.realnamestatus = data;
  },
  [types.WXOPENID](state, data) { //认证标志
    if (data) {
      sessionStorage.setItem("wxopenid", JSON.stringify(data));
      state.wxopenid = data;
    } else {
      sessionStorage.removeItem("wxopenid");
      state.wxopenid = '';
    }
  },
  [types.WXCODE](state, data) { //认证标志
    if (data) {
      sessionStorage.setItem("wxcode", JSON.stringify(data));
      state.wxcode = data;
    } else {
      sessionStorage.removeItem("wxcode");
      state.wxcode = '';
    }

  },
}
// 最后统一导出
export default {
  state,
  getters,
  actions,
  mutations
}
